<script setup lang="tsx">
import { getAmtApi, amtPageApi } from '@/api/financial'
import type { MerchantListParams } from '@/api/BusinessManagement/types'
import { ElButton } from 'element-plus'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { useI18n } from '@/hooks/web/useI18n'
import { useTable } from '@/hooks/web/useTable'
import { SettlementPoolAmtDict } from '@/utils/dict'
import { useRouter } from 'vue-router'
import Detail from '../withdrawalBillCheck/components/Detail.vue'
import Write from './components/CardWrite.vue'

const { t } = useI18n()
const { push } = useRouter()

const showDrawer = ref(false)
const showPaymentDrawer = ref(false)
const activeTab = ref(0)
const detailId = ref(0)
const type = ref(0)
const saveLoading = ref(false)
const writeRef = ref<ComponentRef<typeof Write>>()

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await amtPageApi({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      state: unref(activeTab) === 0 ? '' : unref(activeTab),
      ...unref(searchParams)
    })
    return {
      list: res.data.list || [],
      total: res.data.total || 0
    }
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList } = tableMethods

const drawerTitle = ref('')

const tabs = [
  {
    label: '全部',
    value: 0
  },
  {
    label: '待核算',
    value: 1
  },
  {
    label: '待确认',
    value: 7
  },
  {
    label: '待打款',
    value: 8
  },
  {
    label: '已打款',
    value: 5
  }
]

const searchRef = ref()

const tabChange = (v) => {
  searchRef.value[0].reset()
  activeTab.value = v
  currentPage.value = 1
  searchParams.value = {}
  getList()
}

const withdrawalAmt = ref<any>({})
const getWithdrawalAmt = async () => {
  const res = await getAmtApi()
  withdrawalAmt.value = res.data
}

const pre = (row) => {
  detailId.value = row.checkBillId
  showDrawer.value = true
}

getWithdrawalAmt()

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'id',
    label: 'ID',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'applyNo',
    label: '申请编号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'merchantKeyword',
    label: '申请商户ID/名称',
    search: {
      componentProps: {
        placeholder: '请输入商户ID/名称'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 150,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div class={'flex items-center'}>{row.nickName}</div>
              <div class={'flex items-center'}>ID:{row.merchantNo}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'cardName',
    label: '账户名称',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'cardNo',
    label: '银行账号',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      width: 220,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div class={'flex items-center'}>{row.bankName}</div>
              <div class={'flex items-center'}>{row.cardNo}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'tradeAmt',
    label: '申请提现金额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'feeAmt',
    label: '手续费',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'checkDeductAmt',
    label: '核算扣费',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'practical',
    label: '实际打款金额',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{(row.tradeAmt - row.feeAmt - row.checkDeductAmt).toFixed(2)}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'state',
    label: '状态',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <div>{row.state && SettlementPoolAmtDict[row.state]}</div>
            </>
          )
        }
      }
    }
  },
  {
    field: 'applyTime',
    label: '申请时间',
    search: {
      component: 'DatePicker',
      componentProps: {
        type: 'datetimerange',
        valueFormat: 'YYYY-MM-DD HH:mm:ss'
      }
    },
    form: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'auditTime',
    label: '打款时间',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 220
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 150,
      fixed: 'right',
      slots: {
        default: (data: any) => {
          const row = data.row as MerchantListParams
          if (row.state === 1) {
            return (
              <>
                <ElButton type="primary" link onClick={() => check(row)}>
                  核算
                </ElButton>
              </>
            )
          } else if (row.state === 7) {
            return (
              <>
                <ElButton type="primary" link onClick={() => check(row)}>
                  重新核算
                </ElButton>
                <ElButton type="primary" link onClick={() => pre(row)}>
                  结算单
                </ElButton>
              </>
            )
          } else if (row.state === 8) {
            return (
              <>
                <ElButton type="primary" link onClick={() => uploadPaymentVoucher(row, '打款')}>
                  打款
                </ElButton>
                <ElButton type="primary" link onClick={() => pre(row)}>
                  结算单
                </ElButton>
              </>
            )
          } else if (row.state === 5) {
            return (
              <>
                <ElButton type="primary" link onClick={() => uploadPaymentVoucher(row, '打款凭证')}>
                  打款凭证
                </ElButton>
                <ElButton type="primary" link onClick={() => pre(row)}>
                  结算单
                </ElButton>
              </>
            )
          }
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  const { applyTime, ...rest } = params
  let applyTimeStart, applyTimeEnd
  if (applyTime && applyTime.length > 0) {
    applyTimeStart = applyTime[0]
    applyTimeEnd = applyTime[1]
  }
  currentPage.value = 1
  searchParams.value = {
    applyTimeStart,
    applyTimeEnd,
    ...rest
  }
  getList()
}

const check = (row) => {
  push(
    `/financial/check?id=${row.id}&withdrawalUserId=${row.withdrawalUserId}&checkBillId=${row.checkBillId}`
  )
}
const uploadPaymentVoucher = (row, title) => {
  type.value = title === '打款' ? 1 : 2
  detailId.value = row.id
  drawerTitle.value = title || ''
  showPaymentDrawer.value = true
}
const save = async () => {
  saveLoading.value = true
  const write = unref(writeRef)
  const res = await write?.submit()
  saveLoading.value = false
  if (!res) {
    return
  }
  write?.reset()
  showDrawer.value = false
  getList()
}
const onClosePaymentDrawer = () => {
  showPaymentDrawer.value = false
  const write = unref(writeRef)
  write?.reset()
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="flex-[3] ml-20px">
      <ElTabs v-model="activeTab" @tab-change="tabChange">
        <div
          v-hasPermi="'GET /withdrawalBill/settlementPool/getAmt'"
          style="background: rgb(24 144 255 / 16.9%)"
          class="flex p-10px mb-4 text-14px font-bold"
        >
          <div class="mr-20">累计申请金额：￥{{ withdrawalAmt.totalApplyAmt }}</div>
          <div>累计已打款金额：￥{{ withdrawalAmt.totalSuccessAmt }}</div>
        </div>
        <ElTabPane v-for="item in tabs" :key="item.value" :label="item.label" :name="item.value">
          <Search
            ref="searchRef"
            :schema="allSchemas.searchSchema"
            @reset="setSearchParams"
            @search="setSearchParams"
          />
          <Table
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :columns="allSchemas.tableColumns"
            :data="dataList"
            :loading="loading"
            @register="tableRegister"
            :pagination="{
              total
            }"
          />
        </ElTabPane>
      </ElTabs>
    </ContentWrap>
    <ElDrawer
      title="结算单预览"
      v-model="showDrawer"
      direction="rtl"
      size="800px"
      @close="showDrawer = false"
    >
      <Detail v-if="showDrawer" :id="detailId" />
    </ElDrawer>
    <ElDrawer
      :title="drawerTitle"
      v-model="showPaymentDrawer"
      direction="rtl"
      size="650px"
      @close="onClosePaymentDrawer"
    >
      <Write ref="writeRef" :id="detailId" :type="type" />
      <template #footer>
        <ElButton @click="onClosePaymentDrawer">{{ t('common.cancel') }}</ElButton>
        <ElButton type="primary" :loading="saveLoading" @click="save">
          {{ t('exampleDemo.save') }}
        </ElButton>
      </template>
    </ElDrawer>
  </div>
</template>
